package com.tanhua.interceptor;

import cn.hutool.core.util.StrUtil;
import com.tanhua.domain.Admin;
import com.tanhua.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class tokenInterceptor implements HandlerInterceptor {

    @Autowired
    private AdminService adminService;


    @Override  //在controller方法之前执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 1 通过请求头Authorization获取token
        String token = request.getHeader("Authorization");
        //token=Bearer eyJhbGciOiJIUzI1NiJ9.eyJtb2JpbGUiOiJhZG1pbiJ9.bJ4ClsJc73QajeUTW7xch5boD2gH_4WWlr8EwYOrQkQ
        if(token!=null){
            //token=eyJhbGciOiJIUzI1NiJ9.eyJtb2JpbGUiOiJhZG1pbiJ9.bJ4ClsJc73QajeUTW7xch5boD2gH_4WWlr8EwYOrQkQ
            token=token.replace("Bearer ","");
        }
        // 2 判断app是否携带了token
        if(StrUtil.isEmpty(token)){
            response.setStatus(401); //权限不足
            return false;
        }
        //3 根据token获取redis中的User
        Admin admin = adminService.tokenfromUser(token);
        //将token赋值给登录用户的属性上
        admin.setToken(token);
        //4 判断token中是否有User
        if(admin==null){
            response.setStatus(401);
            return false;
        }
        //5 将User存在我们的ThreadLocal
        AdminHolder.saveAdmin(admin);

        // 放行
        return true;
    }

    @Override  //controller结束要执行的
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        // 将User从threadlocal删除
        AdminHolder.remove();
    }
}
